package tttrung43.libs.android;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class CommonClass {

	private Context _mContext;
	public CommonClass(Context context) {
		this._mContext = context;
	}

	//Get image from resource drawable when know resource id
	public Bitmap GetBitmapFromDrawable(int resourceid){
		return BitmapFactory.decodeResource(_mContext.getResources(), resourceid);
	}
		
	//Bitmap 2 byte array >>19/06/2012 	 	 
	public byte[] Image2Byte(Bitmap img) {
		try {
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			img.compress(CompressFormat.PNG, 100, output);
			return output.toByteArray();
		} catch (Exception ex) {
			return null;
		}
	}
	
		
	//Byte array 2 Bitmap
	public Bitmap Byte2Image(byte[] data){
		try{
			return BitmapFactory.decodeByteArray(data, 0, data.length);
		}catch(Exception ex){
			return null;
		}		
	}
	
	//Get Drawable from Internet address
	public Drawable LoadImageFromInternet(String imageaddress){
		try{		
			Object _obj = null;
			URL url = new URL(imageaddress);
			_obj = url.getContent();
			InputStream is = (InputStream)_obj;
			return Drawable.createFromStream(is, "image");			
		}catch(Exception ex){
			return null;
		}
	}	
	
	//Check network connection in android
	public boolean CheckNetworkConnection(Context context) {
		ConnectivityManager conn = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (conn.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
				|| conn.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING)
			return true;
		else if (conn.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
				|| conn.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED)
			return false;
		return false;
	}
	
	//Delete Directory include sub directory
	public boolean DoDelete(File path) {
		if (path.isDirectory()) {
			for (File file : path.listFiles()) {
				DoDelete(file);
			}
		}
		return path.delete();
	}
}